package com.fm.financemanage.utils;

import com.alibaba.fastjson.JSONObject;
import com.fm.financemanage.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;

@Slf4j
public class RequestUtil {

    public static <T> T postJson(String url, String jsonParameter, Class<T> resultClass) {
        log.info("请求post-json链接:{}", url);
        log.info("请求post-json参数:{}", jsonParameter);
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        try {
            Response execute = instance.newCall(new Request.Builder().url(url)
                    .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8")
                            , jsonParameter)).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("错误:" + jsonParameter);
        }
        JSONObject resultJson = JSONObject.parseObject(result);
        final Integer code = resultJson.getInteger("code");
        if (code == null || code != 200) {
            log.info("请求post-json响应:{}", result);
            throw new BusinessException("错误:" + resultJson.toJSONString());
        }
        return JSONObject.parseObject(result, resultClass);
    }

    public static <T> T postFormData(String url, LinkedHashMap<String, String> parameter, LinkedHashMap<String, HashMap<String, InputStream>> files, Class<T> resultClass) {
        log.info("请求post-formData链接:{}", url);
        log.info("请求post-formData参数:{}", JSONObject.toJSONString(parameter));
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        final MultipartBody.Builder formDataPart = new MultipartBody.Builder().setType(MultipartBody.FORM);
        parameter.forEach(formDataPart::addFormDataPart);
        files.forEach((k, v) -> v.forEach((k1, v1) -> {
            String[] split = k1.split("@@@");
            try {

                File tempFile = File.createTempFile(UUIDUtil.getRandom32BeginTimePK(), "." + split[1]);
                FileOutputStream fos = new FileOutputStream(tempFile);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = v1.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                fos.flush();
                formDataPart.addFormDataPart(k, split[0], RequestBody.create(MediaType.parse("multipart/form-data"), tempFile));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }));
        try {
            Response execute = instance.newCall(new Request.Builder().url(url)
                    .post(formDataPart.build()).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("请求post-formData响应:{}", result);
        return JSONObject.parseObject(result, resultClass);
    }
}
